﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

using System;
using System.Linq;
using System.Reflection;

namespace MicroApi.Core.Filters
{
    public class AuthorizationFilter : IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            var action = context.ActionDescriptor as ControllerActionDescriptor;
            var authAttribute = action.MethodInfo.GetCustomAttributes<AuthAttribute>()
                .Union(action.ControllerTypeInfo.GetCustomAttributes<AuthAttribute>())
                .FirstOrDefault();
            authAttribute?.OnAuthorization(context);
        }
    }
}
